package com.cloud.open.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.open.dao.AppAuthorizationDao;
import com.cloud.open.entity.AppAuthorization;
import com.cloud.open.service.AppAuthorizationService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  应用授权服务实现类
 * </p>
 *
 * @author wenjin
 * @since 2019-09-25
 */
@Service
public class AppAuthorizationServiceImpl extends ServiceImpl<AppAuthorizationDao, AppAuthorization> implements AppAuthorizationService {

    @Override
    public boolean deleteByResourceIds(List<Integer> resourceIds) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.in(AppAuthorization.RESOURCE_ID, resourceIds);
        return remove(wrapper);
    }

    @Override
    public boolean deleteByAppId(Serializable appId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq(AppAuthorization.APP_ID, appId);
        return remove(wrapper);
    }

    @Override
    public List<AppAuthorization> getByAppId(Integer appId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq(AppAuthorization.APP_ID, appId);
        return list(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveAuthorizations(Integer appId, List<Integer> resourceIds) {
        deleteByAppId(appId);

        List<AppAuthorization> list = new ArrayList<>(resourceIds.size());
        for (Integer resourceId : resourceIds) {
            AppAuthorization appAuthorization = new AppAuthorization();
            appAuthorization.setAppId(appId);
            appAuthorization.setResourceId(resourceId);
            list.add(appAuthorization);
        }
        return saveBatch(list);
    }
}
